package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient1;

    private IVoucherOrderService proxy;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("ifSeckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列
    //private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);

    //线程池
    private ExecutorService seckill_order_executor = Executors.newSingleThreadExecutor();
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    private void init(){
        seckill_order_executor.submit(new VoucherOrderHandler());
    }

    /*private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //1 获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();

                    //2 创建订单
                    handlerVoucherOrder(voucherOrder);
                } catch (InterruptedException e) {
                    log.error("订单异常:", e);
                }
            }
        }
    }*/

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //1 获取消息队列中的订单信息
                    // xReadGroup GROUP g1 c1 count 1 block 2000 STREAM stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );

                    //2 获取失败，结束本次
                    if(list==null || list.isEmpty()){
                        continue;
                    }


                    //3 解析取出的消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();

                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    //4 获取成功，创建订单
                    handlerVoucherOrder(voucherOrder);

                    //5 ACK确认
                    //ack stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());


                } catch (Exception e) {
                    log.error("订单创建异常:", e);
                    handlePendingList();
                }
            }
        }
    }

    private void handlePendingList() {
        while (true) {
            try {
                //1 获取pending队列中的订单信息
                // xReadGroup GROUP g1 c1 count 1 STREAM stream.orders 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create("stream.orders", ReadOffset.from("0"))
                );

                //2 获取失败，说明pendingList中没有消息
                if(list==null || list.isEmpty()){
                    break;
                }

                //3 解析取出的消息
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> values = record.getValue();

                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);

                //4 获取成功，创建订单
                handlerVoucherOrder(voucherOrder);

                //5 ACK确认
                //ack stream.orders g1 id
                stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());

            } catch (Exception e) {
                log.error("订单创建异常:", e);
            }
        }

    }


    /**
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1 查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        //2 判断时间是否开始
        LocalDateTime beginTime = voucher.getBeginTime();
        LocalDateTime endTime = voucher.getEndTime();
        LocalDateTime now = LocalDateTime.now();

        if(!now.isAfter(beginTime) || !now.isBefore(endTime)){
            return Result.fail("不在活动时间内");
        }

        //3 判断余量
        Integer stock = voucher.getStock();
        if(stock<1){
            return Result.fail("优惠券已抢光");
        }

        Long userId = UserHolder.getUser().getId();

        //方案一二三只保留方案三
            // 加锁 --> 下单 --> 解锁
            // 下单为代理对象调用创建订单方法

        //方案一: synchronized锁
        synchronized (id.toString().intern()){
            //使用Aop获取代理对象proxy，代理对象调用createVoucherOrder()方法，防止事务失效
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }


        // 方案二: SimpleRedisLock分布式锁
        SimpleRedisLock redisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        boolean ifLock = redisLock.tryLock(1000);
        if(!ifLock){
            return Result.fail("下单失败");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            redisLock.unlock();
        }


        //方案三: Redisson分布式锁
        RLock lock = redissonClient1.getLock("lock:order:" + userId);
        boolean ifLock = lock.tryLock();
        if(!ifLock){
            return Result.fail("下单失败");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }
    */



   @Override
   public Result seckillVoucher(Long voucherId) {

       Long userId = UserHolder.getUser().getId();
       long orderId = redisIdWorker.getGlobalId("order");

       //1 执行lua脚本
       Long execute = stringRedisTemplate.execute(
               SECKILL_SCRIPT,
               Collections.emptyList(),
               voucherId.toString(), userId.toString(), String.valueOf(orderId)
       );

       assert execute != null;
       int result = execute.intValue();

       //2 判断结果是否为0
           //2.1 不为0 不能购买
       if (result!=0)
           return (result == 1)?Result.fail("库存不足"):Result.fail("已购买过一次！");

       //2.2 为0 可以购买，保存订单信息到redis队列


       /*
       //TODO 保存订单信息到阻塞队列
       //3 生成订单
       VoucherOrder voucherOrder = new VoucherOrder();
       //3.1 设置订单id
       voucherOrder.setId(orderId);
       //3.2 设置用户id
       voucherOrder.setUserId(userId);
       //3.3 设置voucher id
       voucherOrder.setVoucherId(voucherId);

       //4 放入阻塞队列
       orderTasks.add(voucherOrder);
       */

       //5 拿到代理对象
       proxy = (IVoucherOrderService) AopContext.currentProxy();

       //6 返回订单id到前端
       return Result.ok(orderId);

   }


    private void handlerVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient1.getLock("lock:order:" + userId);

        boolean ifLock = lock.tryLock();
        if(!ifLock){
            log.error("获取锁失败");
            return;
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }


    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {

        //4 一人一单判断
        Long id = voucherOrder.getUserId();
        Integer count = query().eq("user_id", id).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if(count>0){
            log.error("已购买过一次！");
            return;
        }

        //5 库存减一
        //升级乐观锁CAS方案 (版本号方案 -> CAS方案 -> CAS库存大于0)
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0) //CAS方案，不再判断stock与前一次查到相等，只判断stock>0
                .update();

        if(!success){
            log.error("抢购失败！");
            return;
        }


        /*
        //6 生成订单
        VoucherOrder voucherOrder = new VoucherOrder();
        //6.1 设置订单id
        long orderId = redisIdWorker.getGlobalId("order:voucher");
        voucherOrder.setId(orderId);
        //6.2 设置用户id
        voucherOrder.setUserId(id);
        //6.3 设置voucher id
        voucherOrder.setVoucherId(voucherOrder);
        */

        //6 保存订单
        save(voucherOrder);

    }
}
